<template>
  <section class="user">
    <div class="container">
      <div class="userBox">
        <TableList :list="list" :column="column">
          <div slot="option" class="noBlueBg">
            <el-form :inline="true" :model="options" class="bottom-border" ref="optionForm">
              <el-form-item label="用户名" prop="username">
                <el-input v-model="options.username" clearable placeholder="请输入用户名" size="mini"></el-input>
              </el-form-item>
              <el-form-item label="姓名" prop="realName">
                <el-input v-model="options.realName" clearable placeholder="请输入姓名" size="mini"></el-input>
              </el-form-item>
              <el-form-item label="手机号码" prop="mobile">
                <el-input v-model="options.mobile" clearable placeholder="请输入手机号码" size="mini"></el-input>
              </el-form-item>
              <el-form-item label="身份" prop="mobile">
                <el-select v-model="options.identityId" placeholder="请选择身份" size="mini" @change="changeID2" clearable>
                  <el-option :label="label" :value="id" v-for="(label,id) in dict['identity']" :key="id" ></el-option>
                </el-select>
              </el-form-item>
              <!-- <el-form-item label="部门" prop="department">
                <el-select v-model="options.departmentId" placeholder="请选择部门" size="mini" clearable>
                  <el-option :label="item.name" :value="item.id+''" v-for="item in departmentOptions2"
                             :key="item.id"></el-option>
                </el-select>
              </el-form-item> -->
<!--              <el-form-item label="群组" prop="groups">-->
<!--                <el-input v-model="options.groups" clearable placeholder="请输入群组" size="mini"></el-input>-->
<!--              </el-form-item>-->
              <el-form-item>
                <el-button type="primary" size="mini" @click="loadList"><span class="el-icon el-icon-search"></span> 查询
                </el-button>
                <el-button size="mini" @click="resetOption('optionForm')"><span
                  class="el-icon el-icon-refresh-left"></span> 重置
                </el-button>
              </el-form-item>
              <el-form-item class="floatRight">
                <el-button size="mini" type="success" @click="add"><span class="el-icon el-icon-plus"></span>新增
                </el-button>
                <!-- <el-button size="mini" type="warning" @click="downloadTab"><span
                  class="el-icon el-icon-download"></span>下载用户表模板
                </el-button>
                <el-button size="mini" type="warning" @click="importTab"><span class="el-icon el-icon-upload2"></span>导入用户表
                </el-button> -->
              </el-form-item>
            </el-form>
          </div>
          <div class="page noBlueBg" slot="bottom">
            <el-pagination
              @size-change="changeSize"
              @current-change="changePage"
              :page-sizes="[20, 50, 100, 200]"
              :current-page="page"
              :page-size="limit"
              layout="sizes,total,prev, pager, next, jumper"
              :total="totals">
            </el-pagination>
          </div>
        </TableList>
      </div>
      <Dialog :cfg="dialogCfg" ref="dialog">
        <el-form :model="editUser" label-width="80px" :inline="true" :rules="rules" ref="addForm">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="editUser.username" clearable placeholder="请输入用户名" size="mini"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="editUser.password" clearable placeholder="请输入密码" size="mini"></el-input>
          </el-form-item>
          <el-form-item label="姓名" prop="realName">
            <el-input v-model="editUser.realName" clearable placeholder="请输入姓名" size="mini"></el-input>
          </el-form-item>
          <el-form-item label="手机号码" prop="mobile">
            <el-input v-model="editUser.mobile" clearable placeholder="请输入手机号码" size="mini"></el-input>
          </el-form-item>
          <el-form-item label="角色" prop="roleId">
            <el-select v-model="editUser.roleId" placeholder="请选择角色" size="mini">
              <el-option :label="item.name" :value="item.id+''" v-for="item in roles"
                         :key="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="身份" prop="identityId">
            <el-select v-model="editUser.identityId" placeholder="请选择身份" size="mini" @change="changeID">
              <el-option :label="label" :value="id" v-for="(label,id) in dict['identity']" :key="id" ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="所属部门" prop="departmentId">
            <el-select v-model="editUser.departmentId" placeholder="请选择部门" size="mini">
              <el-option :label="item.name" :value="item.id+''" v-for="item in departmentOptions"
                         :key="item.id"></el-option>
            </el-select>
          </el-form-item>
<!--          <el-form-item label="群组" prop="groups" class="mbn">-->
<!--            <el-input v-model="editUser.groups" clearable placeholder="请输入群组" size="mini"></el-input>-->
<!--          </el-form-item>-->
          <el-form-item label="是否启用" prop="groups" class="mbn">
            <el-switch
              v-model="editUser.status"
              active-color="#03AAD3"
              inactive-color="#ccc">
            </el-switch>
          </el-form-item>
        </el-form>
      </Dialog>
    </div>
  </section>
</template>

<script>

  import TableList from 'comp/common/TableList';
  import Dialog from 'comp/common/Dialog.vue';


  export default {
    name: "User",
    components: {
      Dialog,
      TableList
    },
    data() {
      var Mobile = (rule, value, callback) => {
        const regMobile = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/;
        if (!value) {
          return callback(new Error("请输入手机号码！"));
        }
        if (!regMobile.test(value)) {
          return callback(new Error("手机号码格式错误！"));
        }
        callback();
      };
      return {
        nav: 'user',

        unitName: this.$kkui.cache.get('unit'),
        dict: this.$kkui.cache.get('dict'),
        orgData: [[], []],
        departmentOptions: [],
        departmentOptions2: [],
        preIdentityId:'',
        roles:[],

        tabHeight: 0,
        options: {
          username: '',
          realName: '',
          mobile: '',
          identityId: '',
          unit: '',
          departmentId: '',
          groups: ''

        },
        list: [],
        limit: 20,
        page: 1,
        pages: 1,
        totals: 0,

        column: [
          {
            prop: 'username',
            label: '用户名'
          },
          {
            prop: 'realName',
            label: '姓名'
          },
          {
            prop: 'mobile',
            label: '手机号码'
          },
          {
            prop: 'identityName',
            label: '当前身份',
            options:[]

          },
          {
            prop: 'roleName',
            label: '当前角色',
            options:[]

          },
          {
            prop: 'department',
            label: '所属部门',

          },
          // {
          //   prop: 'groups',
          //   label: '群组'
          // },
          {
            prop: 'status',
            label: '状态',
            btn: 'switch'
          },
          {
            prop: '',
            label: '操作',
            btn: 'editAndDel',
            del: (id) => {
              this.del(id)
            },
            edit: (data) => {
              this.edit(data)
            }
          }
        ],
        dialogCfg: {},
        editUser: {
          username: '',
          realName: '',
          password: '******',
          mobile: '',
          identityId: '',
          roleId: '',
          departmentId: '',
          groups: '',
          status: true
        },
        rules: {
          username: [
            {required: true, message: '请输入用户名', trigger: 'blur'}
          ],
          realName: [
            {required: true, message: '请输入姓名', trigger: 'blur'}
          ],
          password: [
            {required: true, message: '请输入密码', trigger: 'blur'}
          ],
          mobile: [
            {required: true, validator: Mobile, trigger: "blur" }
          ],
          identityId: [
            {required: true, message: '请选择身份', trigger: 'change'}
          ],
          departmentId: [
            {required: true, message: '请选择所在部门', trigger: 'change'}
          ]
        }
      }
    },
    mounted() {
      this.loadList();
      this.getDepartments();
      this.getRoles();  
    },
    methods: {
      getRoles() {
        this.$server('role.list', {
          limit: this.limit,
          page: this.page
          }).then(data => {
          this.roles = data['rows'];
          // console.log(this.roles);
        })
      },

      changeID(val){
        console.log(val,this.preIdentityId);
        if((['3','4'].indexOf(val)>-1 && ['4'].indexOf(this.preIdentityId)>-1) ||
          ['1','2','5'].indexOf(val)>-1 && ['1','2','3','5'].indexOf(this.preIdentityId)>-1){
          return false
        }

        this.departmentOptions = this.orgData[['4'].indexOf(val)>-1?0:1];
        this.preIdentityId=val;
        this.editUser.departmentId='';
      },
      changeID2(val){
        this.departmentOptions2 = this.orgData[['4'].indexOf(val)>-1?0:1];
        this.options.departmentId='';
      },
      getDepartments() {
        this.$server('org.list').then(data => {
          this.unitName = this.$kkui.cache.get('unit');
          let orgData = [[], []];
          data.forEach(item => {
            if (item.name === '各分中心') {
              orgData[0] = item.children;
            } else {
              item.children.forEach(itm => {
                orgData[1].push({...itm})
              })
            }
          });
          this.orgData = orgData;
        })
      },

      getDepartmentOptions(id) {
        this.departmentOptions = this.orgData[this.orgData.findIndex(item => {
          return item.findIndex(itm => itm.id === id*1) >-1
        })]
      },
      getDepartmentOptions2(id) {
        this.departmentOptions2 = this.orgData[this.orgData.findIndex(item => {
          return item.findIndex(itm => itm.id === id*1) >-1
        })]
      },

      // 更新单位名
      renewUnitName() {
        if (!(this.unitName.trim())) {
          this.$kkui.alert({title: '出错啦！', cont: '当前单位名称为空！'});
          return false;
        }
        this.$server('org.unitName', {
          realName: this.unitName
        }).then(data => {
          this.$kkui.cache.set('unit', this.unitName);
          this.$kkui.msg({
            icon: 1,
            cont: '更新成功！'
          })
        })
      },

      //加载列表
      loadList() {
        this.$server('user.list', {
          limit: this.limit,
          page: this.page,
          ...this.options
        }).then(data => {
          this.list = data['rows'].map(item => {
            return {
              ...item,
              status: item['status'] === '1',
            }
          });
          this.totals = data['total'];
          this.$kkui.loading_deepBlue.hide();
        })
      },

      //新增用户
      add() {
        this.editUser = {
          username: '',
          realName: '',
          password: '',
          mobile: '',
          identityId: '',
          roleId: '',
          departmentId: '',
          groups: '',
          status: true
        };
        this.rules.password[0].required = true;
        this.dialogCfg = {
          title: '新增用户',
          closeShow: true,
          footerShow: true,
          width: 615,
          height: 345,
          bg: true,
          submit: (callback) => {
            this.$refs['addForm'].validate((valid) => {
              if (valid) {
                this.$server('user.add', {
                  ...this.editUser,
                  status: this.editUser.status ? '1' : '0'
                }).then(data => {
                  this.$kkui.msg({
                    icon: 1,
                    cont: '新增成功！'
                  });
                  this.loadList();
                  this.initEditData();
                  typeof callback === 'function' && callback();
                });
              } else {
                return false;
              }
            });
          }
        };
        this.$refs.dialog.show = true;
      },

      //编辑用户
      edit(data) {
        this.preIdentityId=data.identityId;
        this.editUser = {password:'******',...data};
        delete  this.editUser.department;
        delete  this.editUser['identityName'];
        console.log(this.editUser);

        this.rules.password[0].required = false;
        this.getDepartmentOptions(data.departmentId);

        this.dialogCfg = {
          title: '编辑用户',
          closeShow: true,
          footerShow: true,
          width: 615,
          height: 430,
          bg: true,
          submit: (callback) => {
            console.log(1);
            this.$refs['addForm'].validate((valid) => {
              if (valid) {
                if(this.editUser.password==='******'){
                  delete this.editUser.password;
                }
                this.editUser.departmentId=this.editUser.departmentId*1;
                this.editUser.identityId=this.editUser.identityId*1;
                this.editUser.roleId=this.editUser.roleId*1;
                this.$server('user.edit', {
                  ...this.editUser,
                  status: this.editUser.status ? '1' : '0'
                }).then(data => {
                  this.loadList();
                  this.initEditData();
                  typeof callback === 'function' && callback();
                });
              } else {
                return false;
              }
            });
          }
        };
        this.$refs.dialog.show = true;
      },

      //删除用户
      del(id) {
        this.$kkui.alert({
          icon: 0,
          cont: '确定删除此用户吗？',
          callback: () => {
            this.$server('user.del', [id * 1]).then(data => {
              this.$kkui.msg({
                icon: '1',
                cont: '删除成功！'
              });
              this.loadList();
            })
          }
        });
      },

      initEditData() {
        this.editUser = {
          username: '',
          realName: '',
          password: '',
          mobile: '',
          unit: '',
          department: '',
          groups: '',
          status: true
        };
      },

      // 下载模板
      downloadTab() {
        const index = this.$kkui.loading.show();
        this.$server('user.downTemplate', {
          tempalteName: 'sys_user'
        }).then(data => {
          const a = document.createElement('a');
          a.href = data;
          a.style.display = 'none';
          a.target = '_blank';
          a.download = '用户表' + '.xls';
          a.click();
          setTimeout(() => {
            this.$kkui.loading.hide(index);
          }, 3000)
        })
      },

      //导入用户表
      importTab() {
        this.$kkui.submit({
          title: '上传用户表格',
          file: true,
          cont: '1'
        }, formData => {
          this.$kkui.alert({
            icon: 0,
            cont: '导入表格将会替换掉相同手机号的用户数据，确定吗？',
            callback: () => {
              this.$server('user.importTable', formData).then(data => {
                this.$kkui.msg({
                  icon: '1',
                  cont: '导入成功！'
                });
                this.loadList();
              })
            }
          })
        })
      },


      //切换分页
      changePage(page) {
        this.page = page;
        this.loadList();
      },

      changeSize(limit) {
        this.limit = limit;
        this.loadList();
      },

      // 重置option
      resetOption(formName) {
        this.options= {
          username: '',
            realName: '',
            mobile: '',
            identityId: '',
            roleId:'',
            unit: '',
            departmentId: '',
            groups: ''

        };
        this.$refs[formName].resetFields();
        this.loadList();
      },
    }
  }
</script>

<style scoped lang="scss">
  @import "~css/system.scss";
</style>
